<template>
  <el-aside width="200px">
    <el-scrollbar>
      <el-menu
          :default-openeds="[]"
          :default-active="$route.path"
          router
          :uniqueOpened="true"
      >
        <!-- 如果菜单没有子菜单，直接使用 el-menu-item -->
        <el-menu-item v-for="(menu) in menusWithoutChildren" :key="menu.id" :index="menu.path" @click="changeView(menu.path)">

          <el-icon><component :is="menu.icon"></component></el-icon>
          <template #title>{{ menu.name }}</template>

        </el-menu-item>
        <!-- 如果菜单有子菜单，使用 el-sub-menu -->
        <el-sub-menu v-for="(menu) in menusWithChildren" :key="menu.id" :index="menu.id.toString()">
          <template #title>

              <el-icon><component :is="menu.icon"></component></el-icon>
              {{ menu.name }}


          </template>
          <el-menu-item-group>
            <el-menu-item v-for="childMenu in getChildMenus(menu.id)" :key="childMenu.id" :index="childMenu.path" @click="changeView(childMenu.path)">
              <el-icon><component :is="childMenu.icon"></component></el-icon>
              {{ childMenu.name }}
            </el-menu-item>
          </el-menu-item-group>
        </el-sub-menu>


      </el-menu>
    </el-scrollbar>
  </el-aside>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import axios from 'axios';

// 定义菜单项的类型
interface Menu {
  id: number;
  name: string;
  icon: string;
  path: string;
  parentId: number;
}

const menus = ref<Menu[]>([]);
const childMenus = ref<Menu[]>([]);

// 获取菜单数据
axios.get('http://localhost:8080/menu/findAll').then((res) => {
  const data = res.data.data;
  data.forEach((menu: Menu) => {
    if (menu.parentId === 0) {
      menus.value.push(menu);
    } else {
      childMenus.value.push(menu);
    }
  });
});

// 计算属性：获取某个父菜单的所有子菜单
const getChildMenus = (parentId: number) => {
  return computed(() => childMenus.value.filter(menu => menu.parentId === parentId)).value;
};

// 计算属性：获取有子菜单的父菜单
const menusWithChildren = computed(() => {
  return menus.value.filter(menu => getChildMenus(menu.id).length > 0);
});

// 计算属性：获取没有子菜单的父菜单
const menusWithoutChildren = computed(() => {
  return menus.value.filter(menu => getChildMenus(menu.id).length === 0);
});

function changeView(path: string) {
  this.$router.push(path);
}
</script>